package com.wsl.thymeleafinaction.repository;

import com.wsl.thymeleafinaction.domain.User;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author:WangShuliang
 * @Description:   用户资源库
 * @Date:Created in 18:19 2017/12/6
 * @Modified by:
 */
@Repository
public class UserRepositoryImpl  implements  UserRepository{
    private static AtomicLong atomicLong = new AtomicLong();
    private final ConcurrentHashMap<Long,User> userMap = new ConcurrentHashMap<Long,User>();

    public UserRepositoryImpl() {
        User user = new User();
        user.setAge(30);
        user.setName("王书亮");
        this.saveOrUpdateUser(user);
    }

    @Override
    public User saveOrUpdateUser(User user) {
        Long id = user.getId();
        if (id<=0){
            id = atomicLong.incrementAndGet();
            user.setId(id);
        }
        this.userMap.put(id,user);
        return user;
    }

    @Override
    public void deleteUser(Long id) {
        this.userMap.remove(id);
    }

    @Override
    public User getUserById(Long id) {

        return this.userMap.get(id);
    }

    @Override
    public List<User> listUser() {
        return new ArrayList<User>(this.userMap.values());
    }
}